<?php
/**
 * @package PHPKit.
 * @author: mawenpei
 * @date: 2016/7/7
 * @time: 13:57
 */
namespace HuoCore\Helper;

use Illuminate\Http\Request;

class Utility
{
    public static function validateMobile($mobile)
    {
        if(!$mobile) return false;
        if(preg_match("/^13[0-9]{1}[0-9]{8}$|14[0-9]{1}[0-9]{8}$|15[0-9]{1}[0-9]{8}$|18[0-9]{1}[0-9]{8}$|17[0-9]{1}[0-9]{8}$/",$mobile)){
            return true;
        }
        return false;
    }

    public static function validateEmail($email)
    {
        if(!$email) return false;
        if(preg_match("/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/",$email)){
            return true;
        }
        return false;
    }

    public static function validateTime($value,$format='date')
    {
        if(!$value) return false;
        $check = false;
        switch($format){
            case 'date':
                $check = preg_match("/[0-9]{4}-[0-9]{2}-[0-9]{2}/",$value);
                break;
            case 'time':
                $check = preg_match("/[0-9]{2}:[0-9]{2}:[0-9]{2}/",$value);
                break;
            case 'datetime':
                $check = preg_match("/[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}/",$value);
                break;
        }
        return $check ? true : false;
    }

    public static function random($length,$type='alnum',$cunstom='')
    {
        $alnum = '0123456789';
        $alphr = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $all   = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $pool = '';
        switch($type){
            case 'custom':
                $pool = $cunstom ? : $alnum;
                break;
            case 'all':
                $pool = $all;
                break;
            case 'alnum':
                $pool = $alnum;
                break;
            case 'alphr':
                $pool = $alphr;
                break;
            default:
                $pool = $all;
                break;
        }

        return substr(str_shuffle(str_repeat($pool, 5)), 0, $length);
    }

    public static function encrypt(Request $request){
        $sign = $request->input("sign");
        $class = new RSASign();
        if($sign == ""){
            return ['status'=>0,'msg'=>'请传入sign'];
        }
        unset($_POST['sign']);
        ksort($_POST);


        $signStr = json_encode($_POST);

        $signStr = urlencode($signStr);

        $signStr = md5($signStr);

        $signCheckResult = $class->verifySign($signStr, $sign);

        if(!$signCheckResult){
            return ['status'=>0,'msg'=>'sign 验签失败'];
        }

//		查看是否超时
        $timeStamp = $_POST['timestamp'];
        if(!$timeStamp || $timeStamp == '' || time() - strtotime($timeStamp) > 15){
            return ['status'=>0,'msg'=>'请求已过期'];
        }
        return ['status'=>1];
    }
}